package com.imoresoft.agile.top;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.imoresoft.agile.entity.ResultCode;
import com.imoresoft.agile.exception.ProException;
import com.imoresoft.agile.service.BaseService;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.SellerCat;
import com.taobao.api.domain.Shop;
import com.taobao.api.domain.User;
import com.taobao.api.domain.UserSubscribe;
import com.taobao.api.request.AppstoreSubscribeGetRequest;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemUpdateRequest;
import com.taobao.api.request.ItemsGetRequest;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.SellercatsListGetRequest;
import com.taobao.api.request.ShopGetRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.AppstoreSubscribeGetResponse;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemsGetResponse;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.SellercatsListGetResponse;
import com.taobao.api.response.ShopGetResponse;
import com.taobao.api.response.UserGetResponse;

public class TopService extends BaseService {

	private TopClient topClient;

	private TopBatchClient topBatchClient;

	public TopService() {
		this.topClient = new TopClient();
		this.topBatchClient = new TopBatchClient();
	}

	public TopService(boolean isRealEnv, String appkey, String appsecret) {
		this.topClient = new TopClient(isRealEnv, appkey, appsecret);
		this.topBatchClient = new TopBatchClient(isRealEnv, appkey, appsecret);
	}

	public long getOnSaleItemsCount(String sessionId, String nick)
			throws ProException {
		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid";
		request.setFields(fields);
		return topBatchClient.getCount(request, sessionId, nick);
	}

	public List<Item> getAllItems(String sessionId, String nick)
			throws ProException {
		List<Item> allItems = new ArrayList<Item>();
		allItems.addAll(this.getOnSaleItems(sessionId, nick));
		allItems.addAll(this.getInventoryItems(sessionId, nick));
		return allItems;
	}

	public List<Item> getItemsOrderByCertainField(String nick, int num,
			String field, String order) throws ProException {
		ItemsGetRequest request = new ItemsGetRequest();
		String fields = "iid,num_iid,title,pic_url,price,delist_time,volume";
		request.setFields(fields);
		request.setNicks(nick);
		request.setOrderBy(field + ":" + order);
		request.setPageNo(new Long(1));
		request.setPageSize(new Long(num));

		ItemsGetResponse response = null;
		try {
			response = topClient.execute(request, nick);
		} catch (ProException e) {
			e.setType(ResultCode.EXCEPTION);
			e.setDesc(nick + "调用getItemsOrderByCertainField()时发生错误");
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> getItemsOfSpecificSellerCat(String sessionId,
			String visitorNick, String sellerCids) throws ProException {
		List<Item> allItems = new ArrayList<Item>();
		allItems.addAll(this.getOnSaleItemsOfSpecificSellerCat(sessionId,
				visitorNick, sellerCids));
		allItems.addAll(this.getInventoryItemsOfSpecificSellerCat(sessionId,
				visitorNick, sellerCids));
		return allItems;
	}

	public List<Item> getOnSaleItems(String sessionId, String nick)
			throws ProException {
		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setOrderBy("delist_time:desc");

		ItemsOnsaleGetResponse response = null;
		try {
			response = topBatchClient.batchExecute(request, Item.class,
					sessionId, nick);
		} catch (ProException e) {
			e.setType(ResultCode.EXCEPTION);
			e.setDesc(nick + "调用getOnSaleItems()时发生错误");
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> getOnSaleRandomItems(String sessionId, String nick)
			throws ProException {
		Long totalResults = getOnSaleItemsCount(sessionId, nick);
		long pageSize = 10;
		int i = (int) ((totalResults - 1) / pageSize + 1);
		Random random = new Random();
		long startPage = random.nextInt(i) + 0L;// 确保随机生成的页数小于倒数第一页

		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time";
		request.setFields(fields);
		request.setPageNo(startPage);
		request.setPageSize(pageSize);

		ItemsOnsaleGetResponse response = topClient.execute(request, sessionId,
				nick);
		return response.getItems();
	}

	public List<Item> getOnSaleItemsOrderByCertainField(String sessionId,
			String nick, int num, String field, String order)
			throws ProException {
		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setOrderBy(field + ":" + order);
		request.setPageNo(new Long(1));
		request.setPageSize(new Long(num));

		ItemsOnsaleGetResponse response = null;
		try {
			response = topClient.execute(request, sessionId, nick);
		} catch (ProException e) {
			e.setType(ResultCode.EXCEPTION);
			e.setDesc(nick + "调用getOnSaleItemsOrderByCertainField()时发生错误");
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> getOnSaleItemsOfSpecificSellerCat(String sessionId,
			String nick, String sellerCids) throws ProException {
		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setSellerCids(sellerCids);
		request.setOrderBy("delist_time:desc");
		ItemsOnsaleGetResponse response = null;
		try {
			response = topBatchClient.batchExecute(request, Item.class,
					sessionId, nick);
		} catch (ProException e) {
			String desc = nick + "调用上架中sellerCids==" + sellerCids + "的宝贝时失败.";
			e.setDesc(desc);
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> getOnSaleItemsOfSpecificSellerCat(String sessionId,
			String nick, String sellerCids, int num, String oderString)
			throws ProException {
		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setOrderBy(oderString);
		request.setSellerCids(sellerCids);
		request.setPageNo(new Long(1));
		request.setPageSize(new Long(num));
		ItemsOnsaleGetResponse response = null;
		try {
			response = topClient.execute(request, sessionId, nick);
		} catch (ProException e) {
			String desc = nick + "调用上架中sellerCids==" + sellerCids + "的宝贝时失败.";
			e.setDesc(desc);
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> getInventoryItems(String sessionId, String nick)
			throws ProException {
		ItemsInventoryGetRequest request = new ItemsInventoryGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setOrderBy("delist_time:desc");

		ItemsInventoryGetResponse response = null;
		try {
			response = topBatchClient.batchExecute(request, Item.class,
					sessionId, nick);
		} catch (ProException e) {
			String desc = nick + "调用getInventoryItems的宝贝时失败.";
			e.setDesc(desc);
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> getInventoryItemsOfSpecificSellerCat(String sessionId,
			String nick, String sellerCids) throws ProException {
		ItemsInventoryGetRequest request = new ItemsInventoryGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setSellerCids(sellerCids);
		request.setOrderBy("delist_time:desc");
		ItemsInventoryGetResponse response = null;
		try {
			response = topBatchClient.batchExecute(request, Item.class,
					sessionId, nick);
		} catch (ProException e) {
			String desc = nick + "获取仓库中sellerCids=" + sellerCids + "的宝贝时失败";
			e.setDesc(desc);
			throw e;
		}
		if (response.getItems() == null)
			return new ArrayList<Item>();
		return response.getItems();
	}

	public List<Item> searchRandomItems(String nick) throws ProException {
		ItemsGetRequest req = new ItemsGetRequest();
		req.setFields("num_iid,title,nick,pic_url,price");
		req.setNicks("bugxiaoya");
		req.setQ("@@@@@");
		long pageSize = 10;
		ItemsGetResponse response = topClient.execute(req, nick);
		Long totalResults = response.getTotalResults();
		int i = (int) ((totalResults - 1) / pageSize + 1);
		Random random = new Random();
		long startPage = random.nextInt(i) + 0L;
		req.setQ("");
		req.setPageNo(startPage);
		req.setPageSize(pageSize);
		response = topClient.execute(req, nick);
		return response.getItems();
	}

	/**
	 * 根据iid List获取itemList
	 * 
	 * @throws ProException
	 * @throws ApiException
	 */
	public List<Item> getItemsWithIids(String sessionId, String nick,
			List<String> numIidList) throws ProException {
		List<Item> itemList = new ArrayList<Item>();
		int erroNum = 0;
		for (String iid : numIidList) {
			Item item = null;
			try {
				item = getItem(sessionId, nick, iid);
			} catch (ProException e) {
				erroNum++;
				logger.warn(e.getMessage());
				if (erroNum == numIidList.size()) {
					String desc = "获取" + erroNum + "个静态推广宝贝全部出错";
					throw new ProException(ResultCode.BUSSINESS_EXCEPTION,
							desc, e.getCode(), e.getMsg(), e.getSubCode(), e
									.getSubMsg());
				}
			}
			if (item != null)
				itemList.add(item);
			// itemList.add(new Item());
		}
		return itemList;
	}

	/**
	 * 根据numIid获取item
	 * 
	 * @param sessionId
	 * @param nick
	 * @param numIid
	 * @return
	 * @throws ProException
	 * @throws ApiException
	 */
	public Item getItem(String sessionId, String nick, String numIid)
			throws ProException {
		ItemGetRequest req = new ItemGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		req.setFields(fields);
		req.setNumIid(Long.valueOf((numIid)));
		ItemGetResponse rsp = null;
		try {
			rsp = topClient.execute(req, sessionId, nick);
		} catch (ProException e) {
			String desc = nick + "获取num_iid=" + numIid + "的宝贝时失败";
			e.setDesc(desc);
			throw e;
		}
		return rsp.getItem();
	}

	public List<SellerCat> getSellerCats(String nick) throws ProException {
		SellercatsListGetRequest request = new SellercatsListGetRequest();
		request.setNick(nick);
		SellercatsListGetResponse response = topClient.execute(request, nick);
		return response.getSellerCats();
	}

	public void updateItemDesc(String sessionId, String nick, long numIid,
			String desc) throws ProException {
		ItemUpdateRequest updateRequest = new ItemUpdateRequest();
		updateRequest.setNumIid(numIid);
		updateRequest.setDesc(desc);
		try {
			topClient.execute(updateRequest, sessionId, nick);
		} catch (ProException e) {
			String errorDesc = nick + "更新宝贝信息报错,numIid=" + numIid;
			e.setType(ResultCode.EXCEPTION);
			e.setDesc(errorDesc);
			throw e;
		}
	}

	public UserSubscribe getSubscribeInfo(String nick, Long leaseId)
			throws ProException {
		AppstoreSubscribeGetRequest request = new AppstoreSubscribeGetRequest();
		request.setNick(nick);
		if (leaseId == null) {
			leaseId = TopConstants.LEASE_ID;
		}
		request.setLeaseId(leaseId);
		AppstoreSubscribeGetResponse response;
		try {
			response = topClient.execute(request, nick);
		} catch (ProException e) {
			e.setType(ResultCode.EXCEPTION);
			e.setDesc(nick + "调用getSubscribeInfo时出现错误");
			throw e;
		}
		return response.getUserSubscribe();
	}

	public Shop getShop(String nick) throws ProException {
		ShopGetRequest req = new ShopGetRequest();
		req
				.setFields("sid,cid,title,nick,desc,bulletin,pic_path,created,modified");
		req.setNick(nick);
		ShopGetResponse response = topClient.execute(req, nick);
		return response.getShop();
	}

	public String getShopURL(String nick) {
		Shop shop = null;
		try {
			shop = getShop(nick);
		} catch (ProException e) {
			logger.error(e.toString(), e);
		}
		if (shop != null) {
			return "http://shop" + shop.getSid() + ".taobao.com";
		} else {
			return "#";
		}
	}

	public User getUser(String nick, String sessionId) {
		UserGetRequest req = new UserGetRequest();
		req.setFields("location.state,location.city,email,alipay_account,"
				+ "seller_credit,buyer_credit,type");
		req.setNick(nick);
		User user = new User();
		try {
			UserGetResponse response = topClient.execute(req, sessionId, nick);
			user = response.getUser();
		} catch (ProException e) {
			logger.warn(nick + "调用getUser时出现错误");
		}
		return user;
	}
}
